package com.stu.mall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.stu.mall.common.to.es.SkuEsModel;
import com.stu.mall.search.config.GmallElasticSearchConfig;
import com.stu.mall.search.constant.EsConstant;
import com.stu.mall.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ProductSaveServiceImpl implements ProductSaveService {

    @Autowired
    private RestHighLevelClient esRestClient;

    @Override
    public boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {
        //1.在es中建立索引，建立号映射关系（doc/json/product-mapping.json）
        // [kibana中执行product-mapping.txt，需要ES安装IK分词器]
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel model : skuEsModels) {
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            indexRequest.id(model.getSkuId() + "");
            indexRequest.source(JSON.toJSONString(model), XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        BulkResponse bulkResponse = esRestClient.bulk(bulkRequest, GmallElasticSearchConfig.COMMON_OPTIONS);
        //toto 如果想在这里处理批量的错误
        boolean b = bulkResponse.hasFailures();
        List<Integer> collect = Arrays.stream(bulkResponse.getItems()).map(BulkItemResponse::getItemId).collect(Collectors.toList());
        log.error("商品上架完成ID：{}，返回的数据：{}", collect, bulkResponse);
        return !b;
    }
}
